package com.example.ball;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

import androidx.annotation.Nullable;

@SuppressLint("AppCompatCustomView")
public class ballClass extends ImageView {

    int left, top, x, y; // 记录触摸事件时的位置信息
    String mode; // 判断是移动还是缩放操作
    double oldDistance, currentZoom; // 记录两点触摸时的距离和当前的缩放比例
    float zoom = 1; // 初始缩放比例为1

    public ballClass(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        ballClass myBall = findViewById(R.id.myBall); // 获取ballClass实例
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                left = this.getLeft();   // 获取控件左边缘的坐标
                top = this.getTop();     // 获取控件上边缘的坐标
                x = (int) event.getRawX();  // 获取触摸事件的绝对X坐标
                y = (int) event.getRawY();  // 获取触摸事件的绝对Y坐标
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX, deltaY;
                int currentX = (int) event.getRawX(), currentY = (int) event.getRawY();
                deltaX = (int) currentX - x;  // 计算X轴方向的变化量
                deltaY = (int) currentY - y;  // 计算Y轴方向的变化量
                // 根据变化量重新设置控件的位置
                this.layout(left + deltaX, top + deltaY,
                        left + deltaX + getWidth(),
                        top + deltaY + getHeight());
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDistance = getDistance(event);  // 记录两点触摸时的距离
                mode = "zoom";  // 进入缩放模式
                break;
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_UP:
            case MotionEvent.ACTION_UP:
                mode = "none";  // 结束缩放模式
                currentZoom = zoom;  // 记录当前缩放比例
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode.equals("zoom")) {
                    double newDistance = getDistance(event);  // 获取两点触摸时的新距离
                    zoom = (float) (currentZoom * newDistance / oldDistance);  // 计算缩放比例
                    myBall.setScaleX(zoom);  // 设置X轴方向的缩放
                    myBall.setScaleY(zoom);  // 设置Y轴方向的缩放
                }
                break;
        }

        return true;
    }

    // 计算两点触摸时的距离
    private double getDistance(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return Math.sqrt(x * x + y * y);
    }

}
